import allure
from selenium.common import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

from page.base_page import BasePage


class OverdueStatistics(BasePage):
    __order_management = By.XPATH, "//*[text()='订单管理']"
    __proxy_order = By.XPATH, "//*[text()='代理订单']"
    __proxy_order_list = By.XPATH, "//*[@href = '/order/proxyOrder/proxyOrderApply']"
    __overdue_amount_summary = By.XPATH, "//*[@class='mb10 search-button']/div"
    __repayment_details_report = By.XPATH, '//*[@href="/statistics/proxyReport/repaymentDetails"]'
    __overdue_details_report = By.XPATH, '//*[@href="/statistics/proxyReport/overdueDetails"]'

    def goto_proxy_order(self):
        from page.proxy_order_apply_page import ProxyOrderApply
        with allure.step('点击订单管理'):
            self.find_and_click(self.__order_management)
        with allure.step('点击代理订单'):
            self.find_and_click(self.__proxy_order)
        with allure.step('点击订单列表'):
            self.find_and_click(self.__proxy_order_list)
            self.wait(EC.visibility_of_element_located((By.XPATH, "//*[text()='借贷人姓名']")), time_out=10)
        return ProxyOrderApply(self.driver)

    def goto_overdue_details_report(self):
        from page.overdue_details_report import OverdueDetailsReport
        with allure.step("点击逾期明细报表"):
            self.find_and_click(self.__overdue_details_report)
        return OverdueDetailsReport(self.driver)

    def get_overdue_amount_summary(self):
        with allure.step("获取逾期明细汇总数据"):
            while True:
                try:
                    overdue_summary = []
                    for i in range(1, 5):
                        overdue_summary.append(
                            (self.find(By.XPATH, f"//*[@class='el-row']/div[{i}]/div").text.split(':'))[1])
                    break
                except (StaleElementReferenceException, IndexError):
                    pass
        return overdue_summary

    def get_product_overdue_details(self, product_name):
        with allure.step(f"获取{product_name}的逾期详情"):
            product_overdue_details = []
            try:
                self.wait(EC.presence_of_element_located((By.XPATH, f"//*[text()='{product_name}']")))
                for i in range(4, 8):
                    product_overdue_details.append(
                        self.find(By.XPATH, f"//*[text()='{product_name}']/../../td[{i}]/div").text)
            except StaleElementReferenceException:
                pass
        return product_overdue_details
